package com.dap.dao.interceptor;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.PreparedStatementHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 获取总记录数的工具类
 * 
 * @author WUDUFENG
 *
 */
public class TotalRecordHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(TotalRecordHelper.class);

    /**
     * 保存计算总行数的值
     */
    private static ThreadLocal<Long> totalRowCountHolder = new ThreadLocal<Long>();

    /**
     * 保存分页查询时是否需要总记录数
     */
    private static ThreadLocal<Boolean> isNeedTotalRowCountHolder = new ThreadLocal<Boolean>() {
        protected Boolean initialValue() {
            return Boolean.FALSE;
        }
    };


    public static boolean isNeadTotalRowCount() {
        return isNeedTotalRowCountHolder.get();
    }


    public static void setNeedTotalRowCount(Boolean isNeedTotalRowCount) {
        isNeedTotalRowCountHolder.set(isNeedTotalRowCount);
    }


    /**
     * 计算查询对象的总行数
     * 
     * @param sql 计算总行数的SQL
     * @param statementHandler
     * @param connection
     * @throws Throwable
     */
    static void computeTotalRecord(String sql, PreparedStatementHandler statementHandler, Connection connection)
            throws Throwable {

        PreparedStatement countStmt = null;
        ResultSet rs = null;
        try {
            countStmt = connection.prepareStatement(sql);
            ParameterHandler parameterHandler = statementHandler.getParameterHandler();
            parameterHandler.setParameters(countStmt);

            rs = countStmt.executeQuery();
            long count = 0L;
            if (rs.next()) {
                count = rs.getLong(1);
            }
            LOGGER.debug("count result : [{}]", count);
            totalRowCountHolder.set(count);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } finally {
                if (countStmt != null) {
                    countStmt.close();
                }
            }
        }
    }


    /**
     * 获取当前线程对应的分页查询的总行数
     * 
     * @return
     */
    public static Long getTotalRecord() {
        Long res = totalRowCountHolder.get();
        if (null == res)
            return 0L;
        return res;
    }
}